package cn.wolfcode.wolf2w.listener;


import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.service.IStratrgyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * redis缓存数据初始化监听器
 * mongodb --> redis
 * 1.攻略统计对象vo
 * 2.用户攻略收藏列表(拓展)
 */
@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    //spring容器启动后马上执行该方法
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStratrgyStatisVORedisService statisVORedisService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("------------攻略vo对象初始化--start----------");

        //1查询mongodb所有攻略
        List<Strategy> list = strategyService.list();
        //2.遍历所有攻略,封装成vo对象
        for (Strategy strategy : list){
            //注:如果第一次初始化后,前端的vo统计对象操作后,与mongodb的数据不一致了
            //在进行第二次初始化,会将第一次的vo对象覆盖掉
            //要做判断,是否存在vo,存在则跳过,不再初始化
            if (statisVORedisService.isExistsStrategyVO(strategy.getId())){
                continue;
            }
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy,vo);
            vo.setStratrgyId(strategy.getId());
            //3.将vo对象设置到redis缓存中
            statisVORedisService.setStrategyStatisVO(vo);
        }
        System.out.println("------------攻略vo对象初始化--end--------------");
    }
}
